package org.hd.rolelist.controller;

import cn.dev33.satoken.util.SaResult;
import org.hd.rolelist.service.RoleListService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("/roleList/")
public class RoleListController {

    @Resource
    RoleListService roleListService;

    @GetMapping("getRoleList")
    public SaResult getRoleList(){

        Map<String, Object> roleList = roleListService.getRoleList();
        if(roleList == null){
            return SaResult.error("未查到角色列表");
        }
        return new SaResult(200,"获取角色列表成功",roleList);
    }

    @PostMapping("changeRoleStatus")
    public SaResult changeRoleStatus(
            @RequestBody Map<String,Object> map
    ){
        if (roleListService.changeRoleStatus((String)map.get("roleName"),(Boolean) map.get("flag"))){
            return SaResult.ok("修改角色状态成功");
        }
        return SaResult.error("修改角色失败");
    }

    /***
     * 修改权限
     * @param map
     * @return
     */
    @PostMapping("changeRight")
    public SaResult changeRight(@RequestBody Map<String,String> map){
        int i = roleListService.changeRight(map.get("roleName"), map.get("rightName"),map.get("oldRight"));
        if(i==1){
            return SaResult.ok("修改成功");
        }else if(i == 2){
            return SaResult.error("权限重复，请检查");
        }
        return SaResult.error("修改失败");
    }


    @Deprecated
    @PostMapping("deleteRight")
    public SaResult deleteRight(@RequestBody Map<String,String> map){
        boolean b = roleListService.deleteRight(map.get("roleName"), map.get("rightName"));
        if(b){
            return SaResult.ok("删除成功");
        }
        return SaResult.error("删除失败");
    }

    /***
     * 删除角色
     * @param map
     * @return
     */
    @PostMapping("deleteRole")
    public SaResult deleteRole(@RequestBody Map<String,String> map){
        boolean flag = roleListService.deleteRole(map.get("roleName"));
        if(flag){
            return SaResult.ok("角色删除成功");
        }
        return SaResult.error("角色删除失败");
    }

    /***
     * 新增角色
     * @return
     */
    @PostMapping("insertNewRole")
    public SaResult insertRole(
            @RequestBody Map<String,Object> map){
        ArrayList<String> arr = (ArrayList<String>)map.get("role");
        int insertResult = roleListService.insertNewRole((String) map.get("roleName"), arr);
        if(insertResult == 1){
            return SaResult.ok("新建成功");
        }else if(insertResult == 2){
            return SaResult.error("角色名重复");
        }else{
            return SaResult.error("新建失败");
        }
    }


}
